import Taro, {Component, Config} from '@tarojs/taro'
import {View, Text, Image} from '@tarojs/components'
import NavbarBlock from "../../common/components/navbarBlock";
import bg from "../../common/assets/navbar_bg4@2x.png";
import authorityIcon from "../../common/assets/my_jurisdiction_icon@2x.png";
import successIcon from "../../common/assets/my_jurisdiction_success@2x.png";

import headerIcon from "../../common/assets/my_headportrait_ default@2x.png";

import rightBg from "../../common/assets/my_bg@2x.png";
import AuthorityDialog from "./authorityDialog";
import common from "../../common/js/common";
import LoginDialog from "./loginDialog";
import ajax from "../../net/ajax";
import apiObject from "../../net/api";

import './mine.scss'


interface ComponentState {
    currentStatus: number
    isShowDialog: boolean
    name: string,
    company: string
    isShowPop: boolean,
    phoneNumber: string,
    openType: string,
    userInfo: any,
    applyInfo: any,
    canIUseGetUserProfile: boolean
}

export default class Mine extends Component <{}, ComponentState> {

    config: Config = {
        navigationStyle: 'custom',
        navigationBarTitleText: '我的',
        enablePullDownRefresh: true,
        onReachBottomDistance: 50,
        backgroundTextStyle: 'dark',
    };


    constructor(props) {
        super(props);
        this.state = {
            currentStatus: 0,
            isShowDialog: false,
            name: '',
            company: '',
            isShowPop: false,
            phoneNumber: '',
            openType: 'getUserInfo',
            userInfo: '',
            applyInfo: null,
            canIUseGetUserProfile: false
        };
    }

    componentWillMount() {
        console.log("wx.getUserProfile", wx.getUserProfile)

        if (wx.getUserProfile) {
            // console.log("wx.getUserProfile",wx.getUserProfile)
            this.setState({
                canIUseGetUserProfile: true
            })
        }
        this.initPage();
    }

    async initPage() {
        const phoneNumber = common.getPhoneNumber();
        if (phoneNumber) {
            this.setState({
                phoneNumber: phoneNumber
            })
            let userInfo = common.getUserInfo();
            if (userInfo) {
                let openId = await common.getUserOpenId();
                userInfo.openId = openId;
                await common.authLogin(userInfo).then(() => {
                    this.getApplyInfo();
                    common.getUserLevel();
                });
                this.setState({
                    userInfo: userInfo
                })
            } else {
                await Taro.getUserInfo().then((res) => {
                    if (res.errMsg === 'getUserInfo:ok') {
                        common.getWeChatUserInfo(res.encryptedData, res.iv)
                    }
                }).catch(res => {
                    console.log("Taro.getUserInfo catch==>", res);
                    this.setState({
                        isShowPop: true,
                        openType: 'getUserInfo'
                    })
                })
            }
        } else {
            this.setState({
                isShowPop: true,
                openType: 'getPhoneNumber'
            });
        }
    }


    async getApplyInfo() {
        let res = await ajax.post(apiObject.supplierApplyInfo, {});
        if (res.statusCode == 200) {
            let data = res.data;
            if (data) {
                this.setState({
                    applyInfo: res.data
                })
            }
        } else {
            //请求异常
            Taro.showToast({
                title: '请求异常,请重试!',
                icon: 'none',
                duration: 2000
            })
        }
    }

    onSubmitClick(name, company) {
        this.setState({name, company, isShowDialog: false})
        let params = {
            name: name,
            companyName: company
        };
        ajax.post(apiObject.applySupplier, params).then((res) => {
            this.setState({
                applyInfo: res.data
            })
        })
    }

    onCloseDialog() {
        this.setState({
            isShowDialog: false
        })
    }

    onApplyClick() {
        if (this.getUserInfoAndPhone()) {
            this.setState({
                isShowDialog: true
            })
        }
    }

    onPullDownRefresh() {
        this.initPage();
        Taro.stopPullDownRefresh();
    }

    getUserInfoAndPhone() {
        let phone = common.getPhoneNumber();
        let userInfo = common.getUserInfo();
        console.log("getUserInfoAndPhone===>", phone, userInfo)
        if (!phone) {
            this.setState({
                isShowPop: true,
                openType: 'getPhoneNumber'
            })
            return false;
        } else if (!userInfo || userInfo.nickName == '微信用户') {
            this.setState({
                isShowPop: true,
                openType: 'getUserInfo'
            })
            return false;
        } else {
            return true;
        }
    }

    onGetUserInfo() {
        Taro.showLoading({title: '申请中...'});
    }

    getUserInfoCallBack() {
        let that = this;
        Taro.getUserInfo({
            success: function (res) {
                common.setUserInfo(res.userInfo);
                that.setState({
                    isShowPop: true,
                    isShowDialog: false,
                });
                Taro.hideLoading();
            }, fail: function () {
                Taro.hideLoading();
                Taro.showToast({
                    title: '授权失败',
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    }

    onCloseLoginDialog(type = 'check') {
        console.log("onCloseLoginDialog==>", type)
        if (type === 'nocheck') {
            this.setState({
                isShowPop: false
            })
        } else {
            let flag = this.getUserInfoAndPhone();
            console.log("===>flag", flag)
            if (this.getUserInfoAndPhone()) {
                this.setState({
                    isShowPop: false,
                }, () => {
                    this.initPage()
                })
            }
        }
    }

    onSetOpenType() {
        if (this.getUserInfoAndPhone()) {
            this.setState({
                isShowPop: false,
            }, () => {
                this.initPage()
            })
        }
    }

    onRefreshInfo() {
        const userInfo = common.getUserInfo();
        this.setState({
            isShowPop: false,
            userInfo: userInfo
        })
    }

    onLoginOutClick() {
        common.removeCache();
        Taro.reLaunch({url: '/pages/index/index'});
    }

    render() {
        let {currentStatus, isShowDialog, isShowPop, openType, userInfo, applyInfo} = this.state;
        return (
            <View className='mine-container'>
                <NavbarBlock title={'我的'}>
                    <Image className='top-bg' mode='widthFix' src={bg}/>
                    <View className='user-info-content'>
                        {userInfo.avatarUrl &&
                        <Image className='user-head' mode='aspectFill' src={userInfo.avatarUrl}/>}
                        {!userInfo.avatarUrl && <Image className='user-head' mode='aspectFill' src={headerIcon}/>}
                        <View className='info-content'>
                            <Text className='name'>{userInfo.nickName || '水果家族'}</Text>
                            <Text className='des'>您好,欢迎光临</Text>
                            <Image className='right-bg' mode='aspectFill' src={rightBg}/>
                        </View>
                    </View>
                    <View className='authority-content'>
                        <Image className='authority-icon' mode='widthFix' src={authorityIcon}/>
                        <Text className='authority-title'>权限申请</Text>
                        {applyInfo === null &&
                        <Text className='authority-status-0' onClick={this.onApplyClick.bind(this)}>立即申请</Text>}
                        {applyInfo && applyInfo.auditStatus == 1 &&
                        <Text className='authority-status-1'>权限申请中...</Text>}
                        {applyInfo && applyInfo.auditStatus == 2 && <View className='authority-status-2'>
                            <Text className='title'>申请成功</Text>
                            <Image className='icon' mode='widthFix' src={successIcon}/>
                        </View>}
                        {applyInfo && applyInfo.auditStatus == 3 && <Text className='authority-status-3' onClick={this.onApplyClick.bind(this)}>失败，重新申请</Text>}
                    </View>

                    <View className='authority-content-x' onClick={this.onLoginOutClick.bind(this)}>退出登录</View>
                </NavbarBlock>

                {isShowDialog && <AuthorityDialog
                    onGetUserInfo={this.onGetUserInfo.bind(this)}
                    getUserInfoCallBack={this.getUserInfoCallBack.bind(this)}
                    onSubmitClick={this.onSubmitClick.bind(this)}
                    onCloseDialog={this.onCloseDialog.bind(this)}
                />}
                {isShowPop &&
                <LoginDialog
                    openType={openType}
                    onSetOpenType={this.onSetOpenType.bind(this)}
                    onRefreshInfo={this.onRefreshInfo.bind(this)}
                    onCloseLoginDialog={this.onCloseLoginDialog.bind(this)}/>}
            </View>
        )
    }
}
